const app = getApp();
let utils = {
  scene_decode: function (scene) {
    let _str = String(scene);
    let _str_list = _str.split(',');
    let res = {};
    for (let i in _str_list) {
      let _tmp_str = _str_list[i];
      let _tmp_str_list = _tmp_str.split(':');
      if (_tmp_str_list.length > 0 && _tmp_str_list[0]) {
        res[_tmp_str_list[0]] = _tmp_str_list[1] || null;
      }
    }
    return res;
  },
  downLoad: function (that) {
    let list = that.data.goods.pic_list;
    wx.showModal({
      title: '提示',
      content: '是否要下载该商品的轮播图片',
      success: function (res) {
        if (res.confirm) {
          if (!wx.saveImageToPhotosAlbum) {
            wx.showModal({
              title: '提示',
              content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
              showCancel: false,
            });
            return;
          }
          wx.getSetting({
            success(res) {
              if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
                loopDownLoad(list);
              } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
                that.setData({
                  open_setting: true,
                });
              } else {
                loopDownLoad(list);
              }
            },
          });
        }
      },
    });
  },
  judgeUserRole() {
    let openid = wx.getStorageSync('OPENID');
    let userRole = '';
    let sellerInfo = '';
    app.util.request({
      url: 'card/api/have_cared',
      data: { openid },
      success: function (res) {
        if (res.data.errno === 0) {
          userRole = res.data.data.issale === '1' ? 'seller' : '';
          sellerInfo = res.data.data;
          app.ws_micro_shop_globalData.userRole = userRole;
          app.ws_micro_shop_globalData.sellerInfo = sellerInfo;
        } else {
          userRole = 'customer';
          sellerInfo = res.data.data;
          app.ws_micro_shop_globalData.userRole = userRole;
          app.ws_micro_shop_globalData.sellerInfo = sellerInfo;
        }
      },
      fail: function (res) {
        userRole = 'customer';
        sellerInfo = res.data.data;
        app.ws_micro_shop_globalData.userRole = userRole;
        app.ws_micro_shop_globalData.sellerInfo = sellerInfo;
      },
    });
  },
  formatTime(date) {
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
  
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
  
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
  },
  formatData(date) {
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
  
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();

    return [year, month, day].map(formatNumber).join('-');
  },
  objectToUrlParams(obj) {
    let str = '';
    for (let key in obj) {
      str += '&' + key + '=' + obj[key];
    }
    return str.substr(1);
  },
  gatherAction(name, result = 'success', data = {}) {
    app.v8_card_seller_actions_log.push({ name, result, data, timestamp: Math.floor(Date.now() / 1000) });
  },
  reportAction() {
    let data = app.v8_card_seller_actions_log;
    data instanceof Array && data.length > 0 && app.util.statRequest({
      pt: getCurrentPages().pop().route,
      pm: JSON.stringify(getCurrentPages().pop().options),
      tm: 0,
      cn: 'click',
      tp: 2,
      aa: JSON.stringify(data),
      is_module: 1,
    });
    app.v8_card_seller_actions_log = [];
  },
  getLeaveTime(leftTime) {
    let days = parseInt(leftTime / 3600 / 24, 10);
    let hours = parseInt(leftTime / 3600 % 24, 10);
    let minutes = parseInt(leftTime / 60 % 60, 10);
    let seconds = parseInt(leftTime % 60, 10);
    days = checkTime(days);
    hours = checkTime(hours);
    minutes = checkTime(minutes);
    seconds = checkTime(seconds);
    return {
      days,
      hours,
      minutes,
      seconds,
    }
  },
  before(vm) {
    vm.setData({
      loadingText: '正在加载',
    });
  },
  after(ret,vm, pageSize = 10,) {
    if (!ret.data.list || ret.data.list.length<=0 || ret.data.list.length<pageSize) {
      vm.setData({
        loadingText: '—— 到底啦 ——',
        canPullUp: false,
      });
    } else {
      vm.setData({
        loadingText: '下拉加载',
        canPullUp: true,
      });
    }
  },
};
function checkTime(pmsI) {
  let i = pmsI;
  i = i > 0 ? i : 0;
  if (i < 10) {
    i = '0' + i;
  }
  return i;
}
function loopDownLoad(list) {
  list.forEach((val, key) => {
    let url = val.pic_url || val;
    if (url.indexOf('myqcloud') !== -1) {
      let index = url.indexOf('image');
      url = app.siteInfo.attachment_url + url.substr(index);
    }
    wx.downloadFile({
      url,
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            if (key === list.length - 1) {
              wx.showToast({
                title: '下载完成',
              });
            }
          },
        });
      },
      fail: function () {
        wx.showToast({
          title: '下载失败',
          icon: 'none',
        });
      },
    });
  });
}
function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
}
module.exports = utils;